package com.api.util

import com.api.config.APIConfig
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.base.config.BaseConfig
import java.util.*

class TokenUtils {
    companion object {
        fun encode(uid: String?): String? {
            return if (uid.isNullOrEmpty())
                null
            else
                try {
                    val date = Date()
                    JWT.create()
                            .withHeader(
                                    mapOf(
                                            "alg" to "HS256",
                                            "typ" to "JWT",
                                    )
                            )
                            .withClaim("uid", uid)
                            .withIssuedAt(date)
                            .withExpiresAt(Date(date.time + BaseConfig.signTokenExpire))
                            .sign(Algorithm.HMAC256(APIConfig.tokenKey))
                } catch (e: Exception) {
                    null
                }
        }

        fun decode(token: String?): String? {
            return if (token.isNullOrEmpty())
                null
            else
                try {
                    JWT.require(Algorithm.HMAC256(APIConfig.tokenKey)).build().verify(token).claims["uid"]?.asString()
                } catch (e: Exception) {
                    null
                }
        }
    }
}
